<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 
<html><head> 
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  <title>上传文件大小限定 (web.py)</title> 
  <link rel="stylesheet" type="text/css" href="/static/webpy-new.css"/> 
  <link rel="SHORTCUT ICON" href="/static/favicon.ico"/> 
</head><body> 
 
        <div id="header"><table class="header"><tr>
                <td class="logo"><a href="/" title="Home"><img src="/static/webpy.gif" alt="" /></a></td> 
<td class="blurb">&ldquo;Think about the ideal way to write a web app.<br />Write the code to make it happen.&rdquo; [<a href="/philosophy">more...</a>]</td> </tr>
</table>
        </div> 
        <div id="location"> 
                <a href="/">home</a> &gt; 上传文件大小限定
        </div> 
<div id="container"> 
<div id="sidebar">
<strong>get started:</strong>
<ul class="body">
  <li><a href="/install">install</a></li>
  <li><a href="/docs/0.3/tutorial">tutorial</a></li>
</ul>
<strong>learn more:</strong>
<ul class="body">
<li><a href="/docs/0.3/api">api reference</a></li>
<li><a href="/cookbook/">cookbook</a></li>
<li><a href="/src/">code examples</a></li>
</ul>

<strong>dive in:</strong>
<ul class="body"> 
<li><a href="https://github.com/webpy/webpy">source code</a></li>
<li><a href="http://groups.google.com/group/webpy/">mailing list</a></li>
<li><a href="https://github.com/webpy/webpy/issues">issue tracker</a></li>
</ul>
</div>

<div id="main"> 
<div id="content" class="body"> 
<h1>上传文件大小限定</h1>

<h2>问题</h2>

<p>如何限定上传文件的大小？</p>

<h2>Solution</h2>

<p>web.py 使用<code>cgi</code> 模块来解析用户的输入， 而 <code>cgi</code> 模块对最大输入大小有限制。</p>

<p>下面的代码限制了最大数据输入为 10MB.</p>

<pre><code>import cgi

# Maximum input we will accept when REQUEST_METHOD is POST
# 0 ==&gt; unlimited input
cgi.maxlen = 10 * 1024 * 1024 # 10MB
</code></pre>

<p>请注意这是对POST方法提交数据大小的限制，而不是上传文件大小。当然如果表单中没有其他输入数据，上传文件完全可以达到限制的大小。</p>

<p><code>cgi</code> 模块将会抛出 <code>ValueError</code>异常，如果数据输入的大小超过了 <code>cgi.maxlen</code>。我们可以捕捉该异常而避免显示不友好的错误信息。</p>

<pre><code>class upload:
    def POST(self):
        try:
            i = web.input(file={})
        except ValueError:
            return "File too large"
</code></pre>

<div style="clear: both;"></div> 
 
</div> 
 
</div> 
</div>
        <div id="footer"> 
    <p>started by <a style="color: gray;" href="http://www.aaronsw.com/">Aaron Swartz</a> (<a style="color: black;" href="mailto:webpy@aaronsw.com">webpy@aaronsw.com</a>)</p>

<p><a href="https://github.com/webpy/webpy.github.com/blob/master/cookbook/limiting_upload_size.zh-cn.md">fork this page on GitHub</a></p>
</div> 
 
</body> 
</html> 
